import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

class WidgetUtil {
  /// 判断是否会超出一行
  static bool moreThanOneLine(
    String text,
    TextStyle style, {
    double? width,
    int maxLines = 1,
    bool isTextField = false,
  }) {
    final span = TextSpan(
      children: [
        TextSpan(
          text: text,
          style: style,
        ),
        if (isTextField) // 模拟两宽度的游标大小
          const TextSpan(
            text: '.',
            style: TextStyle(fontSize: 4, height: 1),
          ),
      ],
    );

    final tp = TextPainter(
      text: span,
      maxLines: maxLines,
      textDirection: TextDirection.ltr,
      locale: Localizations.localeOf(Get.context!),
      strutStyle: StrutStyle.fromTextStyle(style, forceStrutHeight: true),
    );

    tp.layout(
      maxWidth: (width ?? 1.sw).floorToDouble(),
    );

    // return tp.size.width >= (width?.floorToDouble() ?? 1.sw);
    return tp.didExceedMaxLines;
  }

  static double getTextHeight(
    String text,
    TextStyle style,
    double maxWidth, {
    bool dealWithEmptyLine = false,
  }) {
    final span = TextSpan(
      children: [
        TextSpan(
          text: text,
          style: style,
        ),
      ],
    );

    final tp = TextPainter(
      text: span,
      maxLines: 999,
      textDirection: TextDirection.ltr,
      locale: Localizations.localeOf(Get.context!),
      strutStyle: StrutStyle.fromTextStyle(style, forceStrutHeight: true),
    );

    tp.layout(maxWidth: maxWidth);
    if (dealWithEmptyLine) {
      final length = text.split('\n').length - 1;
      return tp.height + length * (style.height ?? 0);
    }
    return tp.height;
  }

  static bool moreThanOneLineWithinSwap(
    String text,
    TextStyle style,
    double? width,
    int maxLines,
  ) {
    final count = text.split('\n');
    if (count.length == 1) {
      return moreThanOneLine(text, style, width: width, maxLines: maxLines);
    } else {
      if (count.length > maxLines) {
        return true;
      } else {
        final index = text.lastIndexOf('\n');
        final newText = text.substring(index, text.length).trim();
        return moreThanOneLine(newText, style, width: width);
      }
    }
  }

  static Size boundingTextSize(
    BuildContext context,
    String text,
    TextStyle style, {
    int maxLines = 2 ^ 31,
    double maxWidth = double.infinity,
  }) {
    if (text.isEmpty) {
      return Size.zero;
    }
    final textPainter = TextPainter(
        textDirection: TextDirection.ltr,
        locale: Localizations.localeOf(context),
        text: TextSpan(text: text, style: style),
        maxLines: maxLines)
      ..layout(maxWidth: maxWidth);
    return textPainter.size;
  }
}
